import { uploadSong, queryAllSongs, querySong } from '@/api/song';
import { querySingers, querySinger } from '@/api/user';

const song = {
  state: {
    songDetail: {},
    songs: [],
    mySongs: [],
    singers: [],
    singerDetail: {},
  },
  mutations: {
    UPDATE_SONGS: (state, payload) => {
      state.songs = payload;
    },
    UPDATE_SONG: (state, payload) => {
      state.songDetail = payload;
    },
    UPDATE_SINGERS: (state, payload) => {
      state.singers = payload;
    },
    UPDATE_SINGER: (state, payload) => {
      state.singerDetail = payload;
    },
  },
  actions: {
    addSong(_, payload) {
      return new Promise((resolve, reject) => {
        uploadSong(payload).then((data) => {
          const { meta } = data;
          if (meta.success && meta.code === 6666) {
            resolve(meta);
          } else {
            reject(meta);
          }
        });
      });
    },
    getAllSongs({ commit }) {
      return new Promise((resolve, reject) => {
        queryAllSongs().then((res) => {
          const { meta, data } = res;
          if (meta.success && meta.code === 6666) {
            commit('UPDATE_SONGS', data.songs);
            resolve();
          } else {
            reject(meta);
          }
        });
      });
    },
    getSong({ commit }, sid) {
      return new Promise((resolve, reject) => {
        querySong(sid)
          .then((res) => {
            const { meta, data } = res;
            if (meta.success && meta.code === 6666) {
              commit('UPDATE_SONG', data.payload);
              resolve();
            } else {
              reject(meta);
            }
          });
      });
    },
    getAllSingers({ commit }) {
      return new Promise((resolve, reject) => {
        querySingers().then((res) => {
          const { meta, data } = res;
          if (meta.success && meta.code === 6666) {
            commit('UPDATE_SINGERS', data.singers);
            resolve();
          } else {
            reject(meta);
          }
        });
      });
    },
    getSinger({ commit }, uid) {
      return new Promise((resolve, reject) => {
        querySinger(uid)
          .then((res) => {
            const { meta, data } = res;
            if (meta.success && meta.code === 6666) {
              commit('UPDATE_SINGER', data.payload);
              resolve();
            } else {
              reject(meta);
            }
          });
      });
    },
  },
  getters: {
    songDetail: state => state.songDetail,
    songs: state => state.songs,
    mySongs: state => state.mySongs,
    singers: state => state.singers,
    singerDetail: state => state.singerDetail,
  },
};

export default song;
